package team.lourd.network.system.own.repository.jpa.netel;


import com.querydsl.core.types.dsl.StringPath;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer;
import org.springframework.data.querydsl.binding.QuerydslBindings;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RestResource;
import team.lourd.network.system.own.domain.netel.NEDiagram;
import team.lourd.network.system.own.domain.netel.QNEDiagram;
import team.lourd.network.system.querydsl.ExtendedQuerydslJpaRepository;

import java.io.UnsupportedEncodingException;

public interface NEDiagramRepository extends PagingAndSortingRepository<NEDiagram, Long>, QuerydslBinderCustomizer<QNEDiagram>, QuerydslPredicateExecutor<NEDiagram>, ExtendedQuerydslJpaRepository<NEDiagram, Long> {



    @RestResource(path = "master")
    @Query(value = "select d.* from ne_diagram d left join ne_branch b on d.ne_branch_id=b.id where b.ne_model_id=:nEModelId and b.is_master=:isMaster", nativeQuery = true)
    NEDiagram findByDetailAndIsMaster(@Param("nEModelId") long nEModelId, @Param("isMaster") boolean isMaster);

    default void customize(QuerydslBindings bindings, QNEDiagram model) {
        bindings.bind(String.class).first((StringPath path, String value) -> {
            // 中文乱码解决问题
            try {
                String newValue = new String(value.getBytes("iso-8859-1"), "utf-8");
                return path.contains(newValue);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return null;
            }
        });
    }
}